import { useEffect, useRef, useState } from 'react'
import css from './tab.less'
import React from 'react'

export interface TabItemData<T extends string | number> {
  value: T
  label: string
}
interface BarPosition {
  width: number
  left: number
}
export interface TabProps<T extends string | number> {
  items?: TabItemData<T>[]
  actived?: T
  onChange?: (value: T) => void
}

function TabItem<T extends string | number>(props: { data: TabItemData<T>; actived?: boolean; onActived?: (evt: BarPosition) => void; onClick?: () => void }) {
  const domRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const dom = domRef.current
    const actived = props.actived
    if (!dom || !actived) return
    props.onActived?.({ width: dom.clientWidth, left: dom.offsetLeft })
  }, [props.actived, domRef.current, props.onActived])
  return (
    <div ref={domRef} onClick={props.onClick} className={`${css['item']} ${props.actived ? css['actived'] : ''}`}>
      {props.data.label}
    </div>
  )
}

export default function Tab<T extends string | number>(props: TabProps<T>) {
  const [barPosition, setBarPosition] = useState<BarPosition>(() => ({ width: 0, left: 0 }))
  return (
    <div className={css['box']}>
      {props.items?.map?.((item) => (
        <TabItem
          onClick={() => {
            props.onChange?.(item.value)
          }}
          data={item}
          actived={props.actived == item.value}
          onActived={setBarPosition}
          key={item.value}
        />
      ))}
      <div style={barPosition} className={css['bar']}></div>
    </div>
  )
}
